// pages/dgame1/dgame1.js
const lon = 116.479862
const lat = 39.945773
const tubiao = 'https://www.juquduo.com/static/resourse/dianwei/顺序框1.png';
const gamebg = 'https://www.juquduo.com/static/resourse/yeshou/地图1.jpg'
var list = [] ;
var tempmks = [] ;
var obj = {"msg":list}
// var all  = new Array();
var all  = [];
var aalength;var openid;
var alldd  = [];
var app = getApp()
var winnn = getApp().globalData.winwidth
var heigg = getApp().globalData.winheight
var pointindex = 0;
var pointindextmp = 0;
var xiansuo11 = 1
var animate11 = 1,sitesite,sdsdid

var mks = []

//在Page({})中使用下列代码
Page({
  data:{qiehuan:'../image/game4/tanxian22.png',
    xiansuo:'https://www.juquduo.com/static/resourse/game4/xiansuo.png',isshowbtn:false,
    showmap:true,isshowxiansuo:false,
    modalHidden:true, xiansuocontent:'',
    modalmons:true,
    all:[],teams:[],showrrr:false,
    kedian:true,list:list,game1title:'正在游戏',
    winheight:app.globalData.winheight,
    winwidth:app.globalData.winwidth,
    acid:'',usertype:'',mapscale:'',markers:[],
    poi:[], lat:'', long:'',big:false,left:false,
    touch: {
      distance: 0,
      scale: 0.5,
      baseWidth: null,
      baseHeight: null,
      scaleWidth: null,
      scaleHeight: null
    }
  },
  onLoad:function(options){
    this.setData({
      height: wx.getSystemInfoSync().windowHeight,
      width: wx.getSystemInfoSync().windowWidth
    })
    // 活动id：sdsdid 只触发一次，防止下一次进入时，全局变量变成undefined
    if(pointindex==0){
      sdsdid = options.id;sitesite = options.site
    }
    
    openid = wx.getStorageSync('openid')
    wx.setStorageSync('acidacid', sdsdid)
    // 如果site为1，显示朝阳公园，因为有options,所以不能放到onshow里面
    // 获取的上个页面传的site之后，赋给全局变量，因为下一次进入页面时，没有site、acid参数，只触发一次
    // 有了site就可以确定地图中心点、地图放大倍数，所以判断site
    if(options.site==1){
      sitesite = 1
      this.setData({poi:{ //朝阳公园
        latitude:39.945773,
        longitude:116.479862,
      },acid:sdsdid,usertype:1,mapscale:14.6})
      // ,acid:259
    }
    if(options.site==2){
      sitesite = 2
      this.setData({poi:{ //附近
        latitude:39.958121,
        longitude:116.46656,
      },acid:sdsdid,usertype:1,mapscale:17.3})
      // ,acid:126
    }
    if(options.site==3){
      sitesite = 3
      this.setData({poi:{ //水长城，acid:155
        latitude: 40.410951,
        longitude: 116.310284,
      },acid:sdsdid,usertype:1,mapscale:14.6})
      // ,acid:261
    }
    if(options.site==4){
      sitesite = 4
      this.setData({poi:{ //古北水镇，acid:155
        latitude: 40.648427,
        longitude: 117.273023,
      },acid:sdsdid,usertype:1,mapscale:15.6})
      // ,acid:261
    }
    
    var that = this
    all = this.data.all

    // request加载地图覆盖物
    wx.request({
      // url: 'https://www.juquduo.com/juquduo/start_activity/loading_points',
      url: 'https://www.juquduo.com/juquduo/event/show',
      data:{
        // openid:openid,   // openid:'oQUXz5IDxMpQcBvHaUayzE7Hy0R0',
        activityId:sdsdid,   // activityId:126,
        isRelease:0,
      },
      success(res){
        if(res.code==100){
          wx.showToast({
            title: '暂无数据，稍后再试',
            icon: 'none',
          })
        }
        // all用于传递点位信息，获取all的长度
        var temppid = res.data[0].PointIndex
        console.log('返回值里的pointindex',temppid)
        //一、先排序，因为markers显示要有序
        console.log('openid',openid,'acid',sdsdid,)
        var allll=[]
        all = res.data
        aalength = all.length
        for (var i = 0; i <aalength; i++) {
          for (var y = 0; y <aalength; y++) {
            var ppoid = res.data[i].PointId
            if(ppoid==y){
              // if(ppoid==aalength-1-y){
              allll[y]=res.data[i]  }  }
        }
        all = allll
        that.setData({all:all})
        console.log('排序后',allll)
        var newliea = []
        var point = all
        var y=0
        //把服务器返回的值倒序排一下，用于markers显示
        for (var i = 0; i <point.length; i++) {
          // for (var i = point.length-1; i >-1; i--) {
          y=y+1
          var id = point[i].PointId;
          var latitude = point[i].Lat;  var longitude = point[i].Lng
          var iconPath = tubiao;  var width = '45';  var height = '35'
          var content = '0'+y;  var label = new Array;
          //给标记点上添加文字
          label.push({'content':content,'color':'#ffffff','anchorX':'-7','anchorY':'-32'})
          var item = {id:id,latitude:latitude,longitude:longitude,iconPath:iconPath,width:width,height:height,label:label[0]};
          newliea = newliea.concat(item);
        }
        alldd = newliea
        console.log('markers显示的数组',alldd)

        // 二、判断是否有未完成游戏，如果有，pointindex、xiansuo11都要改
        if(pointindex==0&&temppid!=0){
          wx.showModal({
            title:'检测到有未完成游戏，是否继续？',
            showCancel:true,
            success(res2){
              if (res2.confirm) {
                //如果继续游戏,xiansuo11可以重置
                pointindex=res.data[0].PointIndex
                //如果pid是3，就是已经过了3关，要显示3个marker
                for(var i=0;i<pointindex;i++){
                  mks.push(alldd[i])
                }
                that.setData({markers:mks})
                console.log('重连-pid',pointindex)
                console.log('重连-覆盖物',mks)

                // 传给下个页面的信息，现在没有问题
                // var backxiabiao = aalength-pointindex-1;
                // var backmsg = all[backxiabiao]
                var backmsg = all[pointindex]
                wx.setStorageSync('pointmsg', backmsg);
                pointindextmp = pointindex
                //开始记录位置变化
                 wx.startLocationUpdate({})
                wx.onLocationChange(_locationChangeFn)

              }else{
                console.log('重新开始游戏，pid',pointindex) 
                pointindextmp = pointindex
                //开始记录位置变化
                 wx.startLocationUpdate({})
                wx.onLocationChange(_locationChangeFn) }  }  })  
        }else{
          console.log('不是断线重连',pointindex)
          pointindextmp = pointindex
          //开始记录位置变化
           wx.startLocationUpdate({})
          wx.onLocationChange(_locationChangeFn)
        }
        
        //三、开始把markers显示到页面上，，加载第一个点的标记
        if(pointindex==0){
          console.log('加载第一个点，pid=0')
          mks.push(alldd[0])
        }else{
          for(var i=0;i<alldd.length;i++){
            if(alldd[i].PointId==pointindex-1){
              mks.push(alldd[pointindex-1])
            }
          }
          console.log('加载第'+ pointindex+1 +'个点')
        }
          // that.setData({markers:newliea})
          that.setData({markers:mks})
      }
    })
    // 获取参数，如果没有获取到site，给一个默认值，用于测试
    // if(pointindex==0){
    //   sdsdid = options.site
    //   if(sdsdid==''||sdsdid=='undefined'||sdsdid==undefined){
    //     console.log('没有活动id')
    //     that.setData({acid:126,usertype:1})
    //   } else {
    //     that.setData({acid:options.id,usertype:options.type})
    //     }
    //   console.log('活动id',that.data.acid)
    // }

    //四、位置变化后的逻辑，页面跳转、传参数
    const _locationChangeFn = function(res) {
      console.log(pointindex)
      // 检测位置，用于触发关卡
      wx.getLocation({
        type: 'gcj02',
        success (ress) {
          const latitude = ress.latitude
          const longitude = ress.longitude
          const speed = ress.speed
          const accuracy = ress.accuracy
          that.setData({lat:latitude,long:longitude})
        }
       })
      // 检测距离,同时确保if内容只执行一次,,alldd是覆盖物数组
      if(pointindex==pointindextmp){
        console.log('判断1')
        console.log(alldd)
        for(var i=0;i<alldd.length;i++){
          console.log('序号',pointindex)
          // all和alldd都是排序过的，获取i的值可以获取对应alldd里的下标
          if(all[i].PointId==pointindex){
            console.log('判断2')
          
        // if(Math.abs(that.data.lat-alldd[pointindex].latitude)<0.000201&&Math.abs(that.data.long-alldd[pointindex].longitude)<0.000201){
            if(Math.abs(that.data.lat-alldd[i].latitude)<2.010101&&Math.abs(that.data.long-alldd[i].longitude)<2.010101){
              console.log('判断3')
              console.log('地图检测到的内容数组下标为',i)
              
            //获取对应下标的msg，传到下一个页面 
              // var xiabiao = aalength-pointindex-1;
              // var msg = all[xiabiao]//------------------------需要改回去
              // console.log('传值的序号，倒着传的');
              // console.log(xiabiao);
              var msg = all[pointindex];
              wx.stopLocationUpdate({
                success: (res) => {console.log('停止监听位置改变-11')},
              })
            // 1.页面跳转,PointType为0是线索，显示路标
              if(msg.PointType==0){
                pointindex++,
                console.log('当前关卡，从1开始')
                console.log(pointindex)    
                setTimeout(function(){
                  wx.showModal({
                    title:'雷达探测到附近有线索\r\n请打开摄像头寻找！',
                    showCancel:false,
                    success(){
                      wx.redirectTo({
                        url: '../dcluecard/dsearch'+xiansuo11+'/search',
                      })  }})
                  wx.setStorageSync('pointmsg', msg);
                },10000)
              }
            // PointType为1是问题，显示问题页面
            if(msg.PointType==1){
              pointindex++
              console.log('当前关卡')
              console.log(pointindex)
              setTimeout(function(){
              wx.redirectTo({
                url: '../dgame2/dgame2?pid='+pointindex,
              })
            },10000)
              wx.setStorageSync('pointmsg', msg);
              console.log('跳转到问题页面')
            }
            // PointType为2是怪物，显示怪物页面
            if(msg.PointType==2){
              console.log('判断类型-2',pointindex)
              ++pointindex,
              console.log('当前关卡')
              console.log(pointindex)
              console.log('到达怪兽关卡')
              setTimeout(function(){
                wx.showModal({
                  title:'雷达探测到附近有怪兽出没\r\n请打开摄像头寻找！',
                  showCancel:false,
                  success(){
                    if(animate11==1){
                      wx.redirectTo({
                        url: '../animate/index?pid='+pointindex,
                      })
                      animate11 = 2
                    }else{
                      wx.redirectTo({
                        url: '../animate22/index?pid='+pointindex,
                      })
                    }
                  }
                })
                wx.setStorageSync('pointmsg', msg);
              },10000)
            }
            
            console.log('传给下个页面的值')
            console.log(msg)
            
            // 2.判断，覆盖物全部加载，跳转到其他页面，mks里面会多2个项（不知道哪里来的），所以加2
            if(pointindex>=aalength){
              wx.setStorageSync('isover', true)
            }else{
              wx.setStorageSync('isover', false)
            }
      }}}}
   }
    wx.setNavigationBarTitle({
      title: '正在游戏',
    })
    
  },
  showbutton(){
    this.setData({isshowbtn:!this.data.isshowbtn})
  },
  onShow(){
    var _this = this;
    var all = this.data.all
    _this.setData({markers:mks})
    console.log('页面显示时的覆盖物')
    console.log(mks)

    console.log('sitesite',sitesite)
    if(sitesite==1){
      this.setData({poi:{ //朝阳公园
        latitude:39.945773,
        longitude:116.479862,
      },acid:sdsdid,usertype:1,mapscale:14.6})
    }
    if(sitesite==2){
      this.setData({poi:{ //附近
        latitude:39.958121,
        longitude:116.46656,
      },acid:sdsdid,usertype:1,mapscale:17.3})
    }
    if(sitesite==3){
      this.setData({poi:{ //水长城
        latitude: 40.410951,
        longitude: 116.310284,
      },acid:sdsdid,usertype:1,mapscale:14.6})
    }
    if(sitesite==4){
      this.setData({poi:{ //古北水镇
        latitude: 40.648427,
        longitude: 117.273023,
      },acid:sdsdid,usertype:1,mapscale:15.6})
    }
      _this.setData({markers:mks})
      console.log('加载第', pointindex,'个点')
      _this.setData({markers:mks})//=======================1028
        // pointindex--
        mks.push(alldd[pointindex-1])
        console.log(alldd[pointindex])
        // pointindex++
    
  },
  xiansuo(){
    this.setData({xiansuo:'https://www.juquduo.com/static/resourse/game4/xiansuo_an.png'})
  },
  //点击出现左下角小地图
  qiehuan(){
    wx.navigateTo({
      url: '../map22/index',
    })
  },
  showxiansuo(){
    this.setData({xiansuo:'https://www.juquduo.com/static/resourse/game4/xiansuo_an.png'})
    this.setData({isshowxiansuo:true})
    var xiansuomsg = wx.getStorageSync('pointmsg')
    if(pointindex==0){
      xiansuomsg='请走到起点获取线索'
    }
    console.log(xiansuomsg)
    this.setData({xiansuocontent:xiansuomsg.RightClue})
    if(xiansuomsg.RightClue==''){
      this.setData({xiansuocontent:xiansuomsg.Description})
    }
    
  },
  hidexiansuo(){
    this.setData({isshowxiansuo:false})
  },
  opencamera(){
    wx.redirectTo({
      url: './search',
    })
    this.setData({modalHidden:true})
  },
  zhuye(){
    wx.redirectTo({
      url: '../ayeshou/yeshou',
    })
  },
  //切换底部导航
  mapbtn(){
    this.setData({showmap:true,game1title:'正在游戏'})
  },
  scobtn(){
    this.setData({showmap:false,game1title:'战况'})
    var that = this
    wx.setNavigationBarTitle({
      title: '战况',
    })
    wx.request({
      url: 'https://www.juquduo.com/juquduo/gaming/group_score',
      data:{
        // activityId:sdsdid,
        activityId:259,
        // openid:openid
        // openid:'oQUXz5JGOodzUTbbl8oabLJZBu88'
      },
      success(res){
        console.log('战况：',res.data.GroupInfo)
        // console.log(res.data.Data[1])
        that.setData({teams:res.data.GroupInfo})
      }
    })
  },
  
  onHide(){
    // wx.clearStorageSync()
    // pointindex=pointindex+1
  },
  showmodelsec(){
    this.setData({modalmons:false})
  },
  showrulor(){
    if(this.data.showrrr){
      this.setData({showrrr:false})
    }else{
      this.setData({showrrr:true})
    }
  }
})
